<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      :disabled="formType === 'view'"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-form-item :label="t('mentorPickApply.applyDialog.form.applyMajor')" prop="applyMajor">
        <el-input
          v-model="formData.applyMajor"
          :placeholder="
            t('common.inputTextPlaceholder') + t('mentorPickApply.applyDialog.form.applyMajor')
          "
        />
      </el-form-item>

      <el-form-item :label="t('mentorPickApply.applyDialog.form.deptId')" prop="deptId">
        <el-tree-select
          v-model="formData.deptId"
          :data="deptTree"
          :props="defaultProps"
          check-strictly
          default-expand-all
          :placeholder="
            t('common.selectTextPlaceholder') + t('mentorPickApply.applyDialog.form.deptId')
          "
          value-key="id"
        />
      </el-form-item>

      <el-form-item :label="t('mentorPickApply.applyDialog.form.title')" prop="title">
        <el-input
          v-model="formData.title"
          :placeholder="
            t('common.inputTextPlaceholder') + t('mentorPickApply.applyDialog.form.title')
          "
        />
      </el-form-item>
      <el-form-item
        :label="t('mentorPickApply.applyDialog.form.highestDegree')"
        prop="highestDegree"
      >
        <el-input
          v-model="formData.highestDegree"
          :placeholder="
            t('common.inputTextPlaceholder') + t('mentorPickApply.applyDialog.form.highestDegree')
          "
        />
      </el-form-item>
      <el-form-item
        :label="t('mentorPickApply.applyDialog.form.applicationFormUrl')"
        prop="applicationFormUrl"
      >
        <IMRUpload
          v-model="formData.applicationFormUrl"
          :disabled="formType === 'view'"
          :limit="1"
          :file-type="['pdf']"
        />
      </el-form-item>
      <el-form-item :label="t('mentorPickApply.applyDialog.form.appendixUrl')" prop="appendixUrl">
        <IMRUpload
          v-model="formData.appendixUrl"
          :disabled="formType === 'view'"
          :limit="1"
          :file-type="['pdf']"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button
        v-if="formType === 'apply'"
        @click="submitForm"
        type="primary"
        :disabled="formLoading"
        >{{ t('common.ok') }}</el-button
      >
      <el-button v-if="formType === 'apply'" @click="dialogVisible = false">{{
        t('common.cancel')
      }}</el-button>
      <el-button v-if="formType === 'view'" @click="dialogVisible = false">{{
        t('common.close')
      }}</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { FormRules } from 'element-plus'
import { defaultProps, handleTree } from '@/utils/tree'
import { MentorApplyApi, MentorApplyWithAccountDTO, MentorPickApplyInfoVO } from '@/api/mentorApply'

/** 导师遴选申请/申请信息 */
defineOptions({ name: 'MentorPickApplyDialog' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const deptTree = ref<any[]>([]) // 部门列表
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：view - 查看；apply - 申请
const formData = ref<any>({
  batchId: undefined,
  title: undefined,
  applyMajor: undefined,
  deptId: undefined,
  highestDegree: undefined,
  applicationFormUrl: undefined,
  appendixUrl: undefined
})
const formRules = reactive<FormRules>({
  title: [
    {
      required: true,
      message: t('common.inputTextPlaceholder') + t('mentorPickApply.applyDialog.form.title'),
      trigger: 'blur'
    }
  ],
  applyMajor: [
    {
      required: true,
      message: t('common.inputTextPlaceholder') + t('mentorPickApply.applyDialog.form.applyMajor'),
      trigger: 'blur'
    }
  ],
  deptId: [
    {
      required: true,
      message: t('common.selectTextPlaceholder') + t('mentorPickApply.applyDialog.form.deptId'),
      trigger: 'change'
    }
  ],
  highestDegree: [
    {
      required: true,
      message:
        t('common.inputTextPlaceholder') + t('mentorPickApply.applyDialog.form.highestDegree'),
      trigger: 'blur'
    }
  ],
  applicationFormUrl: [
    {
      required: true,
      message: t('common.uploadFile') + t('mentorPickApply.applyDialog.form.applicationFormUrl'),
      trigger: 'change'
    }
  ],
  appendixUrl: [
    {
      required: true,
      message: t('common.uploadFile') + t('mentorPickApply.applyDialog.form.appendixUrl'),
      trigger: 'change'
    }
  ]
})

const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (type: 'view' | 'apply', row: MentorPickApplyInfoVO) => {
  dialogVisible.value = true
  dialogTitle.value = t('mentorPickApply.applyDialog.title.' + type) + '-' + row.batchName
  formType.value = type
  resetForm()
  formData.value.batchId = row.id
  // 查看时，设置数据
  if (type === 'view') {
    formLoading.value = true
    try {
      const data = await MentorApplyApi.getApplyInfo(row.id)
      if (data.list?.length) {
        formData.value = data.list[0]
      }
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  try {
    // 校验表单
    await formRef.value.validate()
    // 提示
    await ElMessageBox.confirm(
      t('reviewApply.applyDialog.tips'),
      t('common.confirmTitle'),
      {
        confirmButtonText: t('reviewApply.applyDialog.confirmButton'),
        cancelButtonText: t('common.cancel'),
        type: 'warning'
      }
    )
    // 提交请求
    formLoading.value = true
    const data = formData.value as unknown as MentorApplyWithAccountDTO
    await MentorApplyApi.applyWithAccount(data)
    message.success(t('mentorPickApply.applyDialog.submitSuccess'))
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    batchId: undefined,
    title: undefined,
    applyMajor: undefined,
    deptId: undefined,
    highestDegree: undefined,
    applicationFormUrl: undefined,
    appendixUrl: undefined
  }
  formRef.value?.resetFields()
}

const initData = async () => {
  try {
    const data = await MentorApplyApi.getDepartment()
    deptTree.value = handleTree(data)
  } catch {}
}

onMounted(() => {
  initData()
})
</script>
